<template>
  <div style="height: 10vh; background-color: #fff; padding: 10px 20px;">
    <el-card style="height: 100%;">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" @submit.prevent="queryForm">
        <el-form-item label="停车场" prop="parkName">
          <el-select v-model="searchForm.parkName" placeholder="请选择停车场" style="width: 15vh;" filterable clearable>
            <el-option v-for="park in parklotOptions" :key="park.value" :label="park.label" :value="park.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号" prop="carCode">
          <el-select v-model="searchForm.carCode" placeholder="请选择车牌号" style="width: 15vh;" filterable clearable>
            <el-option v-for="car in carCodeOptions" :key="car.value" :label="car.label" :value="car.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付单号" prop="payNumber">
          <el-select v-model="searchForm.payNumber" placeholder="请选择支付单号" style="width: 15vh;" filterable clearable>
            <el-option v-for="pay in payNumberOptions" :key="pay.value" :label="pay.label" :value="pay.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="payWay">
          <el-select v-model="searchForm.payWay" placeholder="请选择支付方式" style="width: 15vh;" filterable clearable>
            <el-option v-for="way in payWayOptions" :key="way.value" :label="way.label" :value="way.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额" prop="payAmount">
          <el-input v-model.number="searchForm.payAmount" placeholder="请输入金额" style="width: 15vh;" clearable type="number" />
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="queryForm">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <el-dialog title="支付二维码" v-model="qrCodeDialogVisible" width="300px" center>
    <div style="text-align: center;">
      <img :src="qrCodeUrl" alt="支付二维码" style="width: 200px; height: 200px;" v-if="qrCodeUrl" />
      <p v-else>二维码生成中...</p>
    </div>
    <template #footer>
      <el-button @click="qrCodeDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <div class="table-container">
      <el-table
          :data="showList"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="parkName" label="停车场" align="center" />
        <el-table-column prop="carCode" label="车牌号" align="center" />
        <el-table-column prop="orderNumber" label="订单编号" align="center" />
        <el-table-column prop="payNumber" label="支付编号" align="center" />
        <el-table-column prop="payTime" label="支付时间" align="center" />
        <el-table-column prop="payWay" label="支付方式" align="center" />
        <el-table-column prop="payAmount" label="支付金额" align="center">
          <template #default="scope">
            {{ formatFee(scope.row.payAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="payButton(scope.row)" :disabled="scope.row.payStatus === 1">
              {{ scope.row.payStatus === 1 ? '已支付' : '支付' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const API_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9999';

// Search options data
const parklotOptions = ref([]);
const carCodeOptions = ref([]);
const payNumberOptions = ref([]);
const payWayOptions = ref([
  { label: '支付宝', value: '支付宝' },
  { label: '微信支付', value: '微信支付' }
]);

// Search form
const searchFormRef = ref(null);
const searchForm = ref({
  parkName: '',
  carCode: '',
  payNumber: '',
  payWay: '',
  payAmount: null
});

// Table data and pagination
const showList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// Multi-selection
const selectedRows = ref([]);
const tableRef = ref(null);

// QR code dialog
const qrCodeDialogVisible = ref(false);
const qrCodeUrl = ref('');

// Format fee as currency
const formatFee = (fee) => {
  if (fee === null || fee === undefined) return '¥0.00';
  return `¥${Number(fee).toFixed(2)}`;
};

// Fetch parking lot options
const fetchParklotOptions = async () => {
  try {
    const { data } = await axios.get(`${API_URL}/v1/parklot/select`);
    if (data.code === 2000) {
      parklotOptions.value = data.response.map(park => ({
        value: park.parkName,
        label: park.parkName
      }));
    } else {
      ElMessage.error('获取停车场列表失败');
    }
  } catch (error) {
    ElMessage.error('获取停车场列表失败');
    console.error('获取停车场列表失败:', error);
  }
};

// Fetch car code options
const fetchCarCodeOptions = async () => {
  try {
    const { data } = await axios.get(`${API_URL}/v1/parkRecord/select`);
    if (data.code === 2000) {
      carCodeOptions.value = [...new Set(data.response.map(record => record.carCode))].map(carCode => ({
        value: carCode,
        label: carCode
      }));
    } else {
      ElMessage.error('获取车牌号列表失败');
    }
  } catch (error) {
    ElMessage.error('获取车牌号列表失败');
    console.error('获取车牌号列表失败:', error);
  }
};

// Fetch pay number options
const fetchPayNumberOptions = async (records) => {
  payNumberOptions.value = [...new Set(records.map(record => record.payNumber))]
      .filter(payNumber => payNumber)
      .map(payNumber => ({
        value: payNumber,
        label: payNumber
      }));
};

// Reset search form
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value = {
    parkName: '',
    carCode: '',
    payNumber: '',
    payWay: '',
    payAmount: null
  };
  currentPage.value = 1;
  queryForm();
};

// Query payment records
const queryForm = async () => {
  loading.value = true;
  try {
    // First fetch park records to ensure predictFee is updated
    await axios.get(`${API_URL}/v1/parkRecord/select`);

    // Then fetch pay records
    const params = {
      ...searchForm.value,
      page: currentPage.value,
      size: pageSize.value
    };
    const { data } = await axios.get(`${API_URL}/v1/payRecord/select`, { params });
    console.log('Response Data:', data);
    if (data.code === 2000) {
      showList.value = (data.response || []).map(item => ({
        ...item,
        payAmount: item.payAmount ? Number(item.payAmount) : null
      }));
      total.value = data.total || 0;
      await fetchPayNumberOptions(data.response || []);
      ElMessage.success('数据加载成功');
    } else {
      ElMessage.error('获取支付记录失败');
      showList.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取支付记录失败');
    console.error('获取支付记录失败:', error.response || error);
    showList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// Generate payment QR code
const payButton = async (row) => {
  try {
    const params = {
      carCode: row.carCode,
      orderNumber: row.orderNumber
    };
    console.log('Pay Request Params:', params);
    const { data } = await axios.get(`${API_URL}/v1/payRecord/code`, { params });
    console.log('Pay Response:', data);
    if (data.code === 2000) {
      ElMessage.success('支付二维码生成成功');
      qrCodeUrl.value = data.response;
      qrCodeDialogVisible.value = true;
    } else {
      ElMessage.error('生成支付二维码失败');
    }
  } catch (error) {
    ElMessage.error('生成支付二维码失败');
    console.error('生成支付二维码失败:', error.response || error);
  }
};

// Handle selection change
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// Handle page change
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryForm();
};

// Initialize data
onMounted(async () => {
  await fetchParklotOptions();
  await fetchCarCodeOptions();
  await queryForm();
});
</script>

<style scoped>
.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px;
}

.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px;
}
</style>